package gorm

import (
	"github.com/jinzhu/gorm"
	"github.com/sirupsen/logrus"
	"smart-sensor-cloud/internal/model"
	"smart-sensor-cloud/pkg/log"
)

type (
	Hook struct {
		DB *gorm.DB
	}
)

func (h *Hook) Exec(entry *logrus.Entry) error {
	item := &model.LogItem{
		CreatedAt: entry.Time,
	}

	data := entry.Data
	if v, ok := data[log.RequestIDFieldKey]; ok {
		item.RequestID = v.(string)
		delete(data, log.RequestIDFieldKey)
	} else {
		return nil
	}

	if v, ok := data[log.UserIDFieldKey]; ok {
		item.UserID = v.(int)

		user, err := model.GetUserByID(v.(int))
		if err != nil {
			return err
		}

		item.Username = user.Username
		item.NickName = user.Name

		role, err := model.GetRoleWithUserIDWithoutRoleMenuRelations(v.(int))
		if err != nil {
			return err
		}
		item.RoleID = int(role.ID)

		delete(data, log.UserIDFieldKey)
	}

	if v, ok := data["ip"]; ok {
		item.IP = v.(string)
		delete(data, "ip")
	}

	if v, ok := data["method"]; ok {
		item.Method = v.(string)
		delete(data, "method")
	}

	if v, ok := data["url"]; ok {
		item.Path = v.(string)
		delete(data, "url")
	}

	if v, ok := data["respond_status"]; ok {
		item.Status = v.(int)
		delete(data, "respond_status")
	}

	if v, ok := data["latency"]; ok {
		item.Latency = v.(int64)
		delete(data, "latency")
	}

	if v, ok := data["user_agent"]; ok {
		item.Agent = v.(string)
		delete(data, "user_agent")
	}

	if v, ok := data["response_body"]; ok {
		item.Response = v.(string)
		delete(data, "response_body")
	}

	return h.DB.Create(item).Error
}

func (h *Hook) Close() error {
	return h.DB.Close()
}
